package com.easy.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ImageUtil {

    private static final String ENDPOINT="oss-cn-beijing.aliyuncs.com";//存储空间
    private static final String BUCKET_NAME="wghbucket0905";//存储空间名
    private static final String ACCESS_KEY_ID="LTAI5t98guBH9Q6jcD2RtfDs";//阿里云账号
    private static final String ACCESS_KEY_SECRET="lpSeKpm7OG2rX2BPEiX20PefDU8eei";//阿里云密钥
    private static final OSS ossClient = new OSSClientBuilder()
            .build("http://"+ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);//创建OSSClient实例
    public static String upload(InputStream is, String fileName){
        //filename 原文件名
        //newFileName 新文件名
        String newFileName = UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."));

        //请求对象
        PutObjectRequest request = new PutObjectRequest
                (BUCKET_NAME, newFileName,is);
        //响应对象
        PutObjectResult result = ossClient.putObject(request);
        return "https://"+BUCKET_NAME+"."+ENDPOINT+"/"+newFileName;

    }

    public static List<String> getFileList(){
        List<String> list = new ArrayList<>();
        ListObjectsRequest request = new ListObjectsRequest(BUCKET_NAME);
        request.setMarker(null);
        request.setMaxKeys(1000);
        ObjectListing objectListing = ossClient.listObjects(request);
        for(OSSObjectSummary objectSummary : objectListing.getObjectSummaries()){
            list.add(objectSummary.getKey());
        }
        return list;
    }
    public static void delete(String fileName){
        ossClient.deleteObject(BUCKET_NAME, fileName);
    }
    public static void deleteList(List<String> fileNamelist){
        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(BUCKET_NAME);
        deleteObjectsRequest.setKeys(fileNamelist);
        ossClient.deleteObjects(deleteObjectsRequest);
    }

    public static void main(String[] args) {
        System.out.println(getFileList());
        delete("23a84098-7ad5-4282-87dd-da2dbf81f887.png");
        System.out.println(getFileList());
    }

}
















